import inpParser
import sys
import json

param_start_flag = "{{"
param_end_flag = "}}"
param_sep = ":"

outputKeywords = ['output', 'nodeoutput', 'elementoutput']


def parseInputParam(inputFilePath):
    inputParams = []
    with open(inputFilePath, 'r') as f:
        for line in f:
            p_start_index = line.find(param_start_flag)
            p_end_index = line.find(param_end_flag)
            if p_start_index >= 0 and p_end_index >= 0:
                p_sep_index = line.find(param_sep, p_start_index, p_end_index)
                if p_sep_index >= 0:
                    param_name = line[p_start_index + 2:p_sep_index]
                    param_value = line[p_sep_index + 1:p_end_index]
                    inputParams.append({
                        "name": param_name,
                        "value": param_value,
                        "type": "number",
                        "org": line[p_start_index:p_end_index+2]
                    })
    return inputParams


def parseOutputParam(inputFilePath):
    outputParams = []
    keywords = inpParser.InputFile(inputFilePath).parse()
    for keyword in keywords:
        if keyword.name in outputKeywords:
            data = keyword.data
            if len(data) > 0:
                for d in data[0]:
                    if d is not None:
                        outputParams.append({
                            "name": d,
                            "type": keyword.name,
                        })
    return outputParams


def buildParamName(keyword):
    name = keyword.name
    parameter = keyword.parameter
    paramName = "*" + name.capitalize()
    for key in parameter:
        if isinstance(parameter[key], bool):
            paramName += ", " + key
        elif isinstance(parameter[key], (int, float, str)):
            paramName += ", " + key + "=" + str(parameter[key])
    return paramName


if __name__ == '__main__':
    inputFilePath = sys.argv[1]
    paramFilePath = sys.argv[2]
    inputParams = parseInputParam(inputFilePath)
    outputParams = parseOutputParam(inputFilePath)
    output = {
        "success": True,
        "data": {
            "input": inputParams,
            "output": outputParams
        }
    }
    with open(paramFilePath, 'w') as f:
        json.dump(output, f)
